from django.contrib.auth.hashers import check_password, make_password
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
# 首页
from django.urls import reverse

from myadmin import models


def myhomeindex(request):
    # 获取所有的二级分类
    erlist = models.Types.objects.exclude(pid=0)
    context = {'erlist':erlist}
    # 获取一级分类
    data = models.Types.objects.filter(pid=0)
    for x in data:
        # 类别下面的x.items  是二级分类
        x.items = models.Types.objects.filter(pid=x.id)
    context['tlist'] = data

    return render(request,'home/index.html',context)




def myhomelist(request,tid):
    # 获取单击事件触发的对象
    ob = models.Types.objects.get(id = tid)
    # 判断
    # 该对象是一级分类还是二级分类
    if ob.pid == 0:
        # 计划数据样式{name:手机,items:[{对象},{}],goodslist:[{},{},{}]}
        data = ob
        data.items = models.Types.objects.filter(pid = data.id)
        # ids  包含一级多个对象的列表
        ids = []
        for x in data.items:
            ids.append(x.id)
        # 获取所有子类的商品（货物goods的tid外键 = 一级分类对象）
        data.goodslist = models.Goods.objects.filter(tid__in=ids)
    else:
        # 二级分类
        #数据样式： {name: 手机, items: [{}, {}], goodslist: [{}, {}, {}]}
        data = models.Types.objects.get(id=ob.pid)
        data.items = models.Types.objects.filter(pid = data.id)
        data.goodslist = models.Goods.objects.filter(tid=ob.id)

    # 分配数据
    context = {'data':data,'ob':ob}
    return render(request,'home/list.html',context)



def myhomeinfo(request,gid):
    ob = models.Goods.objects.get(id = gid)
    context = {'ob':ob}
    return render(request,'home/info.html',context)




def myhomelogin(request):
    # root = request.GET.dict()['path']
    # root = request.GET['path']
    root = request.GET.get('path')
    #
    # print(root)
    print('root',root)
    if request.method == 'POST':
        if (request.POST['vcode']).upper() != (request.session.get('verifycode')).upper():
            return HttpResponse('<script>alert("验证码错误");location.href="/login/"</script>')
        try:
            # 用手机号码获取用户
            ob = models.Users.objects.get(phone=request.POST['phone'])
            # 验证密码
            if check_password(request.POST['password'],ob.password):
                # 执行登陆
                request.session['VipUser'] = {'uid':ob.id,'username':ob.username,'phone':ob.phone,'status':ob.status}
                return HttpResponse("<script>alert('登陆成功');location.href='%s'</script>"%(root))
        except:
            pass
        return HttpResponse('<script>alert("用户名或密码错误");location.href="/login/"</script>')
    else:
        return render(request,'home/login.html')



def myhomelogout(request):
    # 退出登陆
    del request.session['VipUser']
    return HttpResponse("<script>alert('退出成功');location.href='/'</script>")



def myhomeregister(request):
    # 判断请求方法
    if request.method == 'POST':
        try:
            # 接受数据
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')
            # 密码加密
            data['password'] = make_password(data['password'],None,'pbkdf2_sha256')
            # 执行添加
            models.Users.objects.create(**data)
            # 跳转到列表页
            return HttpResponse("<script>alert('注册成功,请登陆');location.href='/login'</script>")
        except:
            return HttpResponse("<script>alert('注册失败');location.href='/register'</script>")
    else:
        # 返回一个注册的页面
        return render(request,'home/register.html')

def sendmsg(request):
    # 接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    # 账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    # 注意事项：
    # （1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    # （2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    # （3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；

    # import urllib2
    import urllib
    import json
    import random
    # 用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account = "C64520477"
    # 密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "78e7b37857104103e73d390d731e66fc"
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000, 99999))
    # 把验证码存入session
    request.session['msgcode'] = code
    text = "您的验证码是：" + code + "。请不要把验证码泄露给其他人。"
    data = {'account': account, 'password': password, 'content': text, 'mobile': mobile, 'format': 'json'}
    req = urllib.request.urlopen(
        url='http://106.ihuyi.com/webservice/sms.php?method=Submit',
        data=urllib.parse.urlencode(data).encode('utf-8')
    )
    content = req.read()
    res = json.loads(content.decode('utf-8'))
    print(res)
    return HttpResponse(res)




# 验证码

# 验证码
def myhomeverifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
       20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
       xy = (random.randrange(0, width), random.randrange(0, height))
       fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
       draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
       rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')




def addrmanage(request):
    userid = request.session['VipUser']['uid']
    ob = models.Address.objects.filter(uid=userid)
    context = {'ob':ob}
    return render(request,'home/order/addrmanage.html',context)



def addrdel(request,id):
    ob = models.Address.objects.get(id=id)
    ob.delete()
    return redirect(reverse('myhome_addrmanage'))




def addredit(request,id):
    ob = models.Address.objects.get(id=id)
    context={'ob':ob}
    return render(request,'home/order/addredit.html',context)




def addreditupdate(request):
    # try:
        # reveive data
        data = request.GET.dict()
        print(data)
        #获取地址对象模型
        a = models.Address.objects.get(id=data['id'])
        a.addressname = data['addressname']
        a.address = data['address']
        a.addressphone = data['addressphone']
        a.status = data['status']
        # 解决只能有一个默认地址的问题
        if data['status'] == '1':
            # //把以前的地址全部修改为非默认
            obs = models.Address.objects.exclude(id=data['id'])
            for i in obs:
                i.status = 0
                i.save()
        # //执行添加
        a.save()
        return JsonResponse({'error': 0, 'msg': '地址添加成功'})
    # except:
    #     return JsonResponse({'error': 1, 'msg': '地址添加失败'})



